package main

import (
	"errors"
	"gitee.com/lywtimer/practice-go/basic/errhandling/filelistingserver/filelisting"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
)

type userError interface {
	error
	Message() string
}

type appHandler func(writer http.ResponseWriter, request *http.Request) error

func errWrapper(handler appHandler) func(http.ResponseWriter, *http.Request) {

	return func(writer http.ResponseWriter, request *http.Request) {
		defer func() {
			if r := recover(); r != nil {
				log.Printf("Http Panic: %v", r)
				code := http.StatusInternalServerError
				http.Error(writer, http.StatusText(code), code)
			}
		}()
		err := handler(writer, request)
		if err != nil {
			code := http.StatusOK
			//判断错误类型是否允许用户读取
			var userErr userError
			if errors.As(err, &userErr) {
				http.Error(writer, userErr.Message(), http.StatusBadRequest)
				return
			}

			switch {
			case os.IsNotExist(err):
				code = http.StatusNotFound
			}
			http.Error(writer, http.StatusText(code), code)
		}
	}
}

func main() {

	http.HandleFunc("/", errWrapper(filelisting.Handler))
	err := http.ListenAndServe(":9999", nil)
	if err != nil {
		panic(err)
	}
}
